package com.qianfeng.shopping.filter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import java.io.IOException;
// urlPatterns 过滤的路径 访问该路径时候才会执行doFilter方法 进行过滤
@WebFilter(filterName = "TestFilter",urlPatterns ={"/*"},dispatcherTypes = DispatcherType.REQUEST,
initParams = {@WebInitParam(name="start",value = "8"),@WebInitParam(name="end",value = "20")})
public class TestFilter implements Filter {
    public TestFilter(){
        System.out.println("TestFilter()");
    }

    public void init(FilterConfig config) throws ServletException {
        System.out.println(config.getInitParameter("start"));
        System.out.println(config.getInitParameter("end"));
        System.out.println("init()");
    }

    public void destroy() {
        System.out.println("destroy()");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        // ip拉黑功能
        String ip = request.getRemoteAddr();
        if ("192.168.60.163".equals(ip)){
            request.setAttribute("msg","该ip地址已经被拉黑");
            request.getRequestDispatcher("login.jsp").forward(request,response);
        }else{
            // 过滤链
            // 当前过滤执行完后会执行下一个过滤器
            chain.doFilter(request, response);
            System.out.println("doFilter()");
        }
    }
}
